﻿namespace Practices.JsonWebToken {
    using System;
    using System.Collections.Generic;
    using System.IdentityModel.Protocols.WSTrust;
    using System.IdentityModel.Tokens;
    using System.Linq;
    using System.Runtime.InteropServices;
    using System.Security;
    using System.Security.Claims;
    using System.Security.Cryptography;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    public partial class Generate : System.Web.UI.Page {
        protected void Page_Load(object sender, EventArgs e) {
            TextBox4.Text = "http://hquep.erp.cnpc";
            TextBox2.Text = "6000";
            TextBox3.Text = "86171992";
            TextBox1.Text = "OUe6jxKjYRLaEuxK6SklUjLU0MSfZK7+0Qf5hDVOAG4";
        }

        protected void Button1_Click(object sender, EventArgs e) {
            TextBox5.Text = GenerateTokenString(TextBox1.Text, int.Parse(TextBox2.Text), TextBox3.Text, "self", TextBox4.Text);
        }

        //protected void Button2_Click(object sender, EventArgs e) {
        //    TextBox1.Text = SecureStringToString(GenerateSecretKey(32));
        //}

        public static string GenerateTokenString(string securityKey, int expiresSeconds, string loginName, string tokenIssuerName, string appliesToAddress) {
            var created = DateTime.UtcNow;
            var expires = created.AddDays(expiresSeconds);
            var claims = new Claim[] { new Claim(ClaimTypes.Name, loginName) };
            var symmetricKey = System.Text.Encoding.UTF8.GetBytes(securityKey);
            var signingKey = new InMemorySymmetricSecurityKey(symmetricKey);
            var signatureAlgorithm = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256";
            var digestAlgorithm = "http://www.w3.org/2001/04/xmlenc#sha256";

            var tokenHandler = new JwtSecurityTokenHandler();
            var tokenDescriptor = new SecurityTokenDescriptor {
                Subject = new ClaimsIdentity(claims),
                TokenIssuerName = tokenIssuerName,
                AppliesToAddress = appliesToAddress,
                Lifetime = new Lifetime(created, expires),
                SigningCredentials = new SigningCredentials(signingKey, signatureAlgorithm, digestAlgorithm)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);
            return tokenString;
        }

        public static SecureString GenerateSecretKey(int length) {
            using (RandomNumberGenerator randomNumberGenerator = RandomNumberGenerator.Create()) {
                byte[] array = new byte[length];
                randomNumberGenerator.GetBytes(array);
                string strIn = System.Convert.ToBase64String(array);
                if (strIn == null) {
                    return null;
                }
                SecureString secureString = new SecureString();
                for (int i = 0; i < strIn.Length; i++) {
                    char c = strIn[i];
                    secureString.AppendChar(c);
                }
                secureString.MakeReadOnly();
                return secureString;
            }
        }

        static string SecureStringToString(SecureString value) {
            IntPtr bstr = Marshal.SecureStringToBSTR(value);

            try {
                return Marshal.PtrToStringBSTR(bstr);
            } finally {
                Marshal.FreeBSTR(bstr);
            }
        }

        static byte[] GetBytes(string str) {
            byte[] bytes = new byte[str.Length * sizeof(char)];
            System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
            return bytes;
        }
    }
}